package com.freeland.client2009.common;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Map;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import org.apache.commons.lang.StringUtils;

public class StringUtil {

	/**
	 * �滻ָ���ַ�
	 * 
	 * @param line
	 *            Դ�ַ�
	 * @param oldString
	 *            ԭ�����ַ�
	 * @param newString
	 *            ��Ҫ�滻���ַ�
	 * @return
	 */
	public static final String replace(String line, String oldString,
			String newString) {
		if (line == null) {
			return null;
		}
		int i = 0;
		if ((i = line.indexOf(oldString, i)) >= 0) {
			char[] line2 = line.toCharArray();
			char[] newString2 = newString.toCharArray();
			int oLength = oldString.length();
			StringBuffer buf = new StringBuffer(line2.length);
			buf.append(line2, 0, i).append(newString2);
			i += oLength;
			int j = i;
			while ((i = line.indexOf(oldString, i)) > 0) {
				buf.append(line2, j, i - j).append(newString2);
				i += oLength;
				j = i;
			}
			buf.append(line2, j, line2.length - j);
			return buf.toString();
		}
		return line;
	}

	/**
	 * 
	 * @param �ж��Ƿ��ǿ��ַ�
	 * @return
	 */
	public static final boolean isEmpty(String s) {
		if (s == null || s.length()==0)
			return true;
		else
			return false;
	}

	/**
	 * ������ת�����ַ�
	 * 
	 * @param value
	 *            ��Ҫת��������
	 * @return
	 */
	public static final String convertNumberToString(Number value) {
		DecimalFormat formatter = new DecimalFormat();
		formatter.setGroupingUsed(false);
		String result = formatter.format(value.doubleValue());
		return result;
	}

	/**
	 * ����ֵ��ΪString[2]
	 */
	public static final String[] splitStr4Oracle(String s) {
		if (s == null)
			return nullStringArray2;
		int length = s.length();
		if (length <= 650)
			return new String[] { s, null };
		String a = s.substring(0, 650);
		String b = s.substring(650, length);
		return new String[] { a, b };
	}

	private static final String[] nullStringArray2 = new String[2];

	/**
	 * ��Stringѹ�� example:com.jbbis.aic.alteration.entity.AlterRequisition ��
	 * integrateOpinion,getIntegrateOpinionInBytes(),setIntegrateOpinionInBytes
	 */
	public static byte[] zip(String s) {
		if (s == null)
			return null;
		try {
			byte[] bytes = s.getBytes("GBK");
			BufferedInputStream in = new BufferedInputStream(
					new ByteArrayInputStream(bytes));
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			BufferedOutputStream out = new BufferedOutputStream(
					new GZIPOutputStream(baos));
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = in.read(buffer)) != -1) {
				out.write(buffer, 0, len);
			}
			in.close();
			out.close();
			return baos.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * ��ѹString
	 */
	public static String unzip(byte[] bytes) {
		if (bytes == null || bytes.length == 0)
			return null;
		try {
			BufferedInputStream in = new BufferedInputStream(
					new GZIPInputStream(new ByteArrayInputStream(bytes)));
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			BufferedOutputStream out = new BufferedOutputStream(baos);
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = in.read(buffer)) != -1) {
				out.write(buffer, 0, len);
			}
			in.close();
			out.close();
			bytes = baos.toByteArray();
			return new String(bytes, "GBK");
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * ���ַ��ʽ����HTML��ʽ
	 * 
	 * @param s
	 * @return
	 */
	public static String str2HtmlFormat(String s) {
		if (s == null)
			return null;
		String temp = replace(s, "\n", "<br>");
		temp = replace(temp, "\t", "&nbsp;&nbsp;&nbsp;&nbsp;");
		return replace(temp, " ", "&nbsp;");
	}

	/**
	 * ȥ���ַ��ǰ��ո�
	 * 
	 * @param str
	 *            �����ַ�
	 * @return ���ַ��ǰ��ո����ַ�
	 */
	public static String trim(String str) {
		if (str == null)
			return null;
		return str.trim();
	}

	/**
	 * ȥ����ߵ�'0'�ַ�
	 * 
	 * @param str
	 * @return
	 */
	public static String leftTrimZero(String str) {
		int len = str.length();
		int st = 0;
		char[] val = str.toCharArray(); /* avoid getfield opcode */
		while ((st < len) && (val[st] == '0')) {
			st++;
		}
		return (st < len + 1) ? str.substring(st) : str;
	}

	/**
	 * ����Ƿ������Ƿ�Ϊ��
	 * 
	 * @param array
	 *            ���м�������
	 */
	public static boolean isArrayEmpty(Object[] array) {

		boolean result = false;
		if (array == null)
			result = true;
		else {
			if (array.length == 0)
				result = false;

		}
		result = false;
		return result;

	}

	/**
	 * ������պ�ȥ���ǰ�����ַ�
	 * 
	 * @param str
	 *            ��Ҫ������ַ�
	 * @return ������ϵ��ַ�
	 */
	public static String trimorempty(String str) {
		String result = "";
		if (str == null)
			result = "";
		else
			result = trim(str);
		return result;

	}

	/**
	 * ���ͷβ��־��ȡ���ַ�
	 * 
	 * @param srcStr
	 *            Դ�ַ�
	 * @param headToken
	 *            ͷ�ַ��־
	 * @param tailToken
	 *            β�ַ��־
	 * @return ���ַ�
	 * 
	 */
	public static String getSubStrByToken(String srcStr, String headToken,
			String tailToken) {
		String result = "";
		int startPos = srcStr.indexOf(headToken);
		int endPos = srcStr.indexOf(tailToken);
		if (startPos >= 0 && endPos > 0 && startPos < endPos) {
			result = srcStr.substring(startPos + headToken.length(), endPos);
		}
		return result;

	}

	public static String[] getSubStrArrayByToken(String srcStr,
			String headToken, String tailToken) {
		// String result = "";
		// int startPos = srcStr.indexOf(headToken);
		//		
		// int endPos = srcStr.indexOf(tailToken);
		// if (startPos >=0 && endPos > 0 && startPos < endPos) {
		// result = srcStr.substring(startPos+headToken.length(), endPos);
		// }
		// return result;
		int matches = Math.min(StringUtils.countMatches(srcStr, headToken),
				StringUtils.countMatches(srcStr, tailToken));

		if (matches == 0) {
			return null;
		} else {
			String[] result = new String[matches];
			String temp = srcStr;
			for (int i = 0; i < matches; i++) {
				result[i] = getSubStrByToken(temp, headToken, tailToken);
				int pos = srcStr.indexOf(tailToken);
				temp = srcStr.substring(pos + tailToken.length());
			}
			return result;
		}

	}

	/**
	 * @author zhangyb ��ݷָ������ַ�����
	 * @param srcStr
	 *            Դ�ַ�
	 * @param delimiters
	 *            �ָ���
	 * @return �ַ�����
	 */
	public static String[] getStrArrayBySpit(String srcStr, String delimiters) {
		String[] result = null;
		int index = 0;
		if (srcStr != null) {
			StringTokenizer stk = new StringTokenizer(srcStr, delimiters);

			if (stk.hasMoreTokens())
				result = new String[stk.countTokens()];
			while (stk.hasMoreTokens()) {
				result[index] = stk.nextToken();
				index++;
			}
		}
		return result;
	}

	/**
	 * ������ 20060101 ���ַ�ת��Ϊ2006-01-01��ʽ ��ʽ���� 20060101 �Ļ���ԭ���ַ�
	 * 
	 * @param date
	 * @return
	 */
	public static String getDateFormat(String date) {
		if (date != null && date.length() == 8) {
			date = date.substring(0, 4) + "-" + date.substring(4, 6) + "-"
					+ date.subSequence(6, date.length());
		}
		return date;
	}


	public static void main(String[] args) {
		String test = "${xxx.dd$}ddd${555.ddd$}";
		String[] substr = getSubStrArrayByToken(test, "${", "$}");
		for (int i = 0; i < substr.length; i++) {
			System.out.println(substr[i]);
		}
	}

	public static String getMapValue(Map map, String key) {
		String value = null;
		if (map.containsKey(key)) {
			if (map.get(key) != null)
				value = map.get(key).toString();
		}
		return trimorempty(value);
	}

	public static String setRegulateNum(String str) {
		String result = "";
		DecimalFormat df = new DecimalFormat("##.##");
		double d = 0.0;
		if (str != null && str.trim().length() > 0) {
			d = Double.parseDouble(str) / 100;
			result = df.format(Double.parseDouble(String.valueOf(d)));
		}
		return result;
	}

	public static String getRegulateNum(String str) {
		String result = "";
		DecimalFormat df = new DecimalFormat("##.##");
		double d = 0.0;
		if (str != null && str.trim().length() > 0) {
			d = Double.parseDouble(str) * 100;
			result = df.format(Double.parseDouble(String.valueOf(d)));
		}
		return result;
	}

	public static String getRegulateNum(double db) {
		String result = "";
		DecimalFormat df = new DecimalFormat("##");
		result = df.format(Double.parseDouble(String.valueOf(db)));
		return result;
	}

	/**
	 * ʮ���Ƶ�IP��ַת��Ϊʮ����Ƶ�IP
	 * 
	 * @author zhangyb
	 * @param ip
	 * @return
	 */
	public static String ip2HexStr(String ip) {
		String hexStr = null;
		String[] ips = getStrArrayBySpit(ip, ".");
		for (int i = 0; i < ips.length; i++) {
			hexStr = hexStr.concat(str2HexStr(ips[i]));
		}
		return hexStr;
	}

	/**
	 * ʮ����Ƶ�IP��ַת��Ϊʮ���Ƶ�IP
	 * 
	 * @param hexStr
	 * @return
	 */
	public static String hexStr2IP(String hexStr) {
		String ip = null;
		String subIP = "";
		if (hexStr.length() == 8) {
			for (int i = 0; i < 4; i++) {
				subIP = hexStr.substring(i * 2, (i + 1) * 2);
				if (i == 0)
					ip = String.valueOf(Integer.parseInt(subIP, 16));
				else
					ip = ip + "." + hexStr2Str(subIP);
			}
		}
		return ip;
	}

	/**
	 * ʮ�����ת��Ϊʮ����
	 * 
	 * @param hexStr
	 * @return
	 */
	public static String hexStr2Str(String hexStr) {
		String str = null;
		str = String.valueOf(Integer.parseInt(hexStr, 16));
		return str;
	}

	/**
	 * ʮ����ת��Ϊʮ�����
	 * 
	 * @param str
	 * @return
	 */
	public static String str2HexStr(String str) {
		String hexStr = "";
		hexStr = Integer.toHexString(Integer.parseInt(str));
		if (hexStr.length() < 2)
			hexStr = "0" + hexStr;
		return hexStr;
	}

	

	public static String getStrForParseInt(String s) {
		String result = trimorempty(s);
		if (result.length() > 0)
			return result;
		else
			return "0";
	}

	/**
	 * �ж��ַ��Ƿ���ڸ���ַ��������
	 * 
	 * @param str
	 * @param aStr
	 * @return
	 */
	public static boolean isSub(String str, String[] aStr) {
		boolean isSub = false;
		if (aStr != null) {
			for (int i = 0; i < aStr.length; i++) {
				if (str.equalsIgnoreCase(aStr[i])) {
					isSub = true;
					break;
				}
			}
		}
		return isSub;
	}

	public static String bigDecimal2Str(BigDecimal bg) {
		String result = "";
		if (bg != null)
			result = bg.toString();
		return result;
	}

	/**
	 * ������
	 * 
	 * @param str
	 * @return 'str'
	 */
	public static String quotedString(String str) {
		return "'" + str + "'";
	}



	/**
	 * ���ַ�����ת��Ϊ�ַ�,��","Ϊ�ָ�
	 * 
	 * @param array
	 * @return
	 */
	public static String array2Str(String[] array) {
		String result = "";
		if ((array != null) || (array.length > 0)) {
			for (int i = 0; i < array.length; i++) {
				if (i > 0)
					result = result + "," + array[i];
				else
					result = array[i];
			}

		}
		return result;
	}
	
	/**
	 * ���ԡ������ָ���ַ�ӡ�����
	 * @param str
	 * @return
	 */
	public static String getSQLStr(String str){
		String result = "";
		String[] strs = null;
		if(str!=null){
			strs = getStrArrayBySpit(str,",");
			for(int i=0;i<strs.length;i++){
				if(i>0)
					result = result.concat(",");
				result = result.concat(quoted(strs[i]));
			}
		}
		return result;
	}
	
	/**
	 * �ӡ�����
	 * @param s
	 * @return
	 */
	public static String quoted(String s){
	   if(s!=null)
		   return "'"+s+"'";
	   else
		   return null;
	}
	
	/**
	   * ���ָ�ʽ��������ϰٷ�λ
	   * @param  number: ��ʽ��ǰ������;
	   * @param  decimalDigits: С��λ��;
	   * @return: ��λһ���Զ��ŷָ���ַ�;
	   */
	public static String format(double number, int decimalDigits) {
		if (number == 0d)
			number = 0d;

		boolean flag = false;
		if (decimalDigits < 0) {
			//С��λ����С��0.
			return "";
		}

		String pattern = "##################";
		if (decimalDigits > 0) {
			flag = true;
			pattern += ".";
			for (int i = 0; i < decimalDigits; i++) {
				pattern += "0";
			}
		}

		DecimalFormat df = new DecimalFormat(pattern);
		if (number <= -1d) {
			return df.format(number);
		} else if (number > -1d && number < 0d) {
			return "-0" + df.format(number).substring(1);
		} else if (number >= 0d && number < 1d) {
			if (flag == true) {
				return "0" + df.format(number);
			} else {
				return df.format(number);
			}
		} else {
			return df.format(number);
		}
	}
	
	public static int convert2Int(String str){
		try{
			int i=Integer.parseInt(str);
			return i; 
		}catch(Exception e){
			return 0;
		}
	}
	
	public static long convert2Long(String str){
		try{
			long i=Long.parseLong(str);
			return i; 
		}catch(Exception e){
			return 0;
		}
	}		
	public static boolean convert2Boolean(String str){
		try{
			boolean i=Boolean.parseBoolean(str);
			return i; 
		}catch(Exception e){
			return false;
		}
	}	
	
	public static double convert2Double(String str){
		try{
			double d = Double.parseDouble(str);
			return d;
		}catch(Exception e){
			return 0;
		}
	}
	
	public static boolean isAlphaNumeric(String str){
		if(str==null)
			return false;
        byte[] bytes = str.getBytes();
		for (int i = 0; i < bytes.length; i++) {
			if (!((bytes[i] >= 48 && bytes[i] <= 57)
					|| (bytes[i] >= 65 && bytes[i] <= 90) || (bytes[i] >= 97 && bytes[i] <= 122))) {
				return false;
			}
		}
		return true;
	}
	
	/**
	 * ȡָ��λ�������ַ�
	 * 
	 * @param length
	 * @return
	 */
	public static String getRandomString(int length) {
		StringBuffer buffer = new StringBuffer(
				"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz");
		StringBuffer sb = new StringBuffer();
		Random r = new Random();
		int range = buffer.length();
		for (int i = 0; i < length; i++) {
			sb.append(buffer.charAt(r.nextInt(range)));
		}
		return sb.toString();
	}
}

